<template>
  <div class="training-page">
    <div class="page-header">
      <h2>培训管理</h2>
      <div class="header-actions">
        <el-button type="primary" icon="Plus" @click="showAddDialog = true">创建培训计划</el-button>
        <el-button icon="Download">导出</el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e8f4ff">
            <el-icon color="#409eff" :size="24"><Reading /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalPrograms }}</div>
            <div class="stat-label">培训计划</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #fff5e8">
            <el-icon color="#fa8c16" :size="24"><User /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.totalParticipants }}</div>
            <div class="stat-label">参训人数</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #e8fff3">
            <el-icon color="#52c41a" :size="24"><CircleCheck /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.completed }}</div>
            <div class="stat-label">已完成</div>
          </div>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="stat-card">
          <div class="stat-icon" style="background: #fff0f0">
            <el-icon color="#ff4d4f" :size="24"><Clock /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stats.ongoing }}</div>
            <div class="stat-label">进行中</div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="培训名称">
          <el-input v-model="filterForm.name" placeholder="请输入培训名称" clearable />
        </el-form-item>
        <el-form-item label="培训类型">
          <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
            <el-option label="入职培训" value="onboarding" />
            <el-option label="技能培训" value="skill" />
            <el-option label="管理培训" value="management" />
            <el-option label="安全培训" value="safety" />
            <el-option label="专业培训" value="professional" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option label="计划中" value="planning" />
            <el-option label="进行中" value="ongoing" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
          <el-button icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 培训列表 -->
    <el-card class="table-card">
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="培训计划" name="programs">
          <el-table :data="programList" stripe>
            <el-table-column prop="name" label="培训名称" width="200" />
            <el-table-column prop="type" label="培训类型" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.typeText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="trainer" label="培训讲师" width="120" />
            <el-table-column prop="startDate" label="开始日期" width="120" />
            <el-table-column prop="endDate" label="结束日期" width="120" />
            <el-table-column prop="duration" label="培训时长" width="100" align="center" />
            <el-table-column prop="participants" label="参训人数" width="100" align="center">
              <template #default="{ row }">
                <el-tag type="primary">{{ row.participants }}人</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="培训地点" width="150" />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">{{ row.statusText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewDetail(row)">详情</el-button>
                <el-button link type="success" @click="viewParticipants(row)">参训人员</el-button>
                <el-button link type="primary" @click="editProgram(row)">编辑</el-button>
                <el-button link type="danger" @click="deleteProgram(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="培训记录" name="records">
          <el-table :data="recordList" stripe>
            <el-table-column prop="employeeName" label="员工姓名" width="120" />
            <el-table-column prop="department" label="部门" width="120" />
            <el-table-column prop="programName" label="培训项目" width="200" />
            <el-table-column prop="trainer" label="培训讲师" width="120" />
            <el-table-column prop="startDate" label="开始日期" width="120" />
            <el-table-column prop="endDate" label="完成日期" width="120" />
            <el-table-column prop="duration" label="培训时长" width="100" align="center" />
            <el-table-column prop="score" label="考核成绩" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getScoreType(row.score)">{{ row.score }}分</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getRecordStatusType(row.status)">{{ row.statusText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewRecord(row)">查看</el-button>
                <el-button link type="success" @click="viewCertificate(row)">证书</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="课程管理" name="courses">
          <el-button type="primary" icon="Plus" @click="showCourseDialog = true" style="margin-bottom: 15px">添加课程</el-button>
          <el-table :data="courseList" stripe>
            <el-table-column prop="name" label="课程名称" width="200" />
            <el-table-column prop="category" label="课程分类" width="120">
              <template #default="{ row }">
                <el-tag>{{ row.category }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="instructor" label="授课讲师" width="120" />
            <el-table-column prop="duration" label="课程时长" width="100" align="center" />
            <el-table-column prop="difficulty" label="难度等级" width="120" align="center">
              <template #default="{ row }">
                <el-rate v-model="row.difficulty" disabled />
              </template>
            </el-table-column>
            <el-table-column prop="credits" label="学分" width="80" align="center" />
            <el-table-column prop="learners" label="学习人数" width="100" align="center" />
            <el-table-column label="操作" fixed="right" width="200">
              <template #default="{ row }">
                <el-button link type="primary" @click="editCourse(row)">编辑</el-button>
                <el-button link type="success" @click="viewCourseContent(row)">课程内容</el-button>
                <el-button link type="danger" @click="deleteCourse(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="培训评估" name="evaluation">
          <el-table :data="evaluationList" stripe>
            <el-table-column prop="programName" label="培训项目" width="200" />
            <el-table-column prop="totalParticipants" label="参训人数" width="100" align="center" />
            <el-table-column prop="completionRate" label="完成率" width="100" align="center">
              <template #default="{ row }">
                <el-progress :percentage="row.completionRate" />
              </template>
            </el-table-column>
            <el-table-column prop="averageScore" label="平均成绩" width="100" align="center">
              <template #default="{ row }">
                <el-tag type="success">{{ row.averageScore }}分</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="satisfaction" label="满意度" width="120" align="center">
              <template #default="{ row }">
                <el-rate v-model="row.satisfaction" disabled show-score />
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="培训成本" width="120" align="center" />
            <el-table-column prop="effectiveness" label="培训效果" width="150">
              <template #default="{ row }">
                <el-tag :type="getEffectivenessType(row.effectiveness)">{{ row.effectivenessText }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="150">
              <template #default="{ row }">
                <el-button link type="primary" @click="viewEvaluation(row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑培训计划对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="dialogTitle"
      width="700px"
    >
      <el-form :model="programForm" :rules="rules" ref="programFormRef" label-width="100px">
        <el-form-item label="培训名称" prop="name">
          <el-input v-model="programForm.name" placeholder="请输入培训名称" />
        </el-form-item>
        <el-form-item label="培训类型" prop="type">
          <el-select v-model="programForm.type" placeholder="请选择类型">
            <el-option label="入职培训" value="onboarding" />
            <el-option label="技能培训" value="skill" />
            <el-option label="管理培训" value="management" />
            <el-option label="安全培训" value="safety" />
            <el-option label="专业培训" value="professional" />
          </el-select>
        </el-form-item>
        <el-form-item label="培训讲师" prop="trainer">
          <el-input v-model="programForm.trainer" placeholder="请输入培训讲师" />
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="startDate">
              <el-date-picker
                v-model="programForm.startDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="endDate">
              <el-date-picker
                v-model="programForm.endDate"
                type="date"
                placeholder="选择日期"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="培训时长" prop="duration">
          <el-input v-model="programForm.duration" placeholder="如：8小时、2天" />
        </el-form-item>
        <el-form-item label="培训地点" prop="location">
          <el-input v-model="programForm.location" placeholder="请输入培训地点" />
        </el-form-item>
        <el-form-item label="培训内容" prop="content">
          <el-input
            v-model="programForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入培训内容"
          />
        </el-form-item>
        <el-form-item label="培训目标" prop="objectives">
          <el-input
            v-model="programForm.objectives"
            type="textarea"
            :rows="3"
            placeholder="请输入培训目标"
          />
        </el-form-item>
        <el-form-item label="考核方式" prop="assessment">
          <el-input v-model="programForm.assessment" placeholder="如：笔试、实操、作业" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加课程对话框 -->
    <el-dialog v-model="showCourseDialog" title="添加课程" width="600px">
      <el-form :model="courseForm" label-width="100px">
        <el-form-item label="课程名称">
          <el-input v-model="courseForm.name" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select v-model="courseForm.category" placeholder="请选择分类">
            <el-option label="技术类" value="tech" />
            <el-option label="管理类" value="management" />
            <el-option label="业务类" value="business" />
            <el-option label="通用类" value="general" />
          </el-select>
        </el-form-item>
        <el-form-item label="授课讲师">
          <el-input v-model="courseForm.instructor" placeholder="请输入授课讲师" />
        </el-form-item>
        <el-form-item label="课程时长">
          <el-input v-model="courseForm.duration" placeholder="如：2小时" />
        </el-form-item>
        <el-form-item label="难度等级">
          <el-rate v-model="courseForm.difficulty" />
        </el-form-item>
        <el-form-item label="学分">
          <el-input-number v-model="courseForm.credits" :min="1" :max="10" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCourseDialog = false">取消</el-button>
        <el-button type="primary" @click="handleCourseSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 统计数据
const stats = reactive({
  totalPrograms: 32,
  totalParticipants: 268,
  completed: 18,
  ongoing: 14
})

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 当前标签页
const activeTab = ref('programs')

// 培训计划列表
const programList = ref([
  {
    id: 1,
    name: '新员工入职培训',
    type: 'onboarding',
    typeText: '入职培训',
    trainer: '张讲师',
    startDate: '2025-02-01',
    endDate: '2025-02-03',
    duration: '3天',
    participants: 15,
    location: '培训室A',
    status: 'ongoing',
    statusText: '进行中'
  },
  {
    id: 2,
    name: 'Java高级开发培训',
    type: 'skill',
    typeText: '技能培训',
    trainer: '李工程师',
    startDate: '2025-01-20',
    endDate: '2025-01-27',
    duration: '7天',
    participants: 20,
    location: '技术培训室',
    status: 'completed',
    statusText: '已完成'
  },
  {
    id: 3,
    name: '团队管理与领导力',
    type: 'management',
    typeText: '管理培训',
    trainer: '王经理',
    startDate: '2025-02-10',
    endDate: '2025-02-12',
    duration: '3天',
    participants: 12,
    location: '会议室B',
    status: 'planning',
    statusText: '计划中'
  }
])

// 培训记录列表
const recordList = ref([
  {
    id: 1,
    employeeName: '张三',
    department: '技术部',
    programName: 'Java高级开发培训',
    trainer: '李工程师',
    startDate: '2025-01-20',
    endDate: '2025-01-27',
    duration: '7天',
    score: 92,
    status: 'completed',
    statusText: '已完成'
  },
  {
    id: 2,
    employeeName: '李四',
    department: '产品部',
    programName: '产品思维培训',
    trainer: '刘讲师',
    startDate: '2025-01-15',
    endDate: '2025-01-18',
    duration: '4天',
    score: 88,
    status: 'completed',
    statusText: '已完成'
  }
])

// 课程列表
const courseList = ref([
  {
    id: 1,
    name: 'Java核心技术',
    category: '技术类',
    instructor: '李工程师',
    duration: '16小时',
    difficulty: 4,
    credits: 4,
    learners: 85
  },
  {
    id: 2,
    name: '团队管理艺术',
    category: '管理类',
    instructor: '王经理',
    duration: '12小时',
    difficulty: 3,
    credits: 3,
    learners: 56
  }
])

// 评估列表
const evaluationList = ref([
  {
    id: 1,
    programName: 'Java高级开发培训',
    totalParticipants: 20,
    completionRate: 95,
    averageScore: 89,
    satisfaction: 4.5,
    cost: '¥15,000',
    effectiveness: 'excellent',
    effectivenessText: '优秀'
  },
  {
    id: 2,
    programName: '产品思维培训',
    totalParticipants: 18,
    completionRate: 88,
    averageScore: 86,
    satisfaction: 4.2,
    cost: '¥12,000',
    effectiveness: 'good',
    effectivenessText: '良好'
  }
])

// 对话框
const showAddDialog = ref(false)
const showCourseDialog = ref(false)
const dialogTitle = computed(() => programForm.id ? '编辑培训计划' : '创建培训计划')
const programFormRef = ref(null)

// 培训表单
const programForm = reactive({
  id: null,
  name: '',
  type: '',
  trainer: '',
  startDate: '',
  endDate: '',
  duration: '',
  location: '',
  content: '',
  objectives: '',
  assessment: ''
})

// 课程表单
const courseForm = reactive({
  name: '',
  category: '',
  instructor: '',
  duration: '',
  difficulty: 3,
  credits: 2
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入培训名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择培训类型', trigger: 'change' }],
  trainer: [{ required: true, message: '请输入培训讲师', trigger: 'blur' }]
}

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    planning: 'info',
    ongoing: 'warning',
    completed: 'success',
    cancelled: 'danger'
  }
  return types[status] || 'info'
}

// 获取成绩类型
const getScoreType = (score) => {
  if (score >= 90) return 'success'
  if (score >= 80) return 'primary'
  if (score >= 60) return 'warning'
  return 'danger'
}

// 获取记录状态类型
const getRecordStatusType = (status) => {
  return status === 'completed' ? 'success' : 'warning'
}

// 获取效果类型
const getEffectivenessType = (effectiveness) => {
  const types = {
    excellent: 'success',
    good: 'primary',
    average: 'warning',
    poor: 'danger'
  }
  return types[effectiveness] || 'info'
}

// 搜索
const handleSearch = () => {
  console.log('搜索', filterForm)
  ElMessage.success('搜索成功')
}

// 重置
const handleReset = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  ElMessage.success('已重置')
}

// 切换标签页
const handleTabClick = (tab) => {
  console.log('切换到', tab.props.name)
}

// 查看详情
const viewDetail = (row) => {
  console.log('查看详情', row)
  ElMessage.info('查看详情功能')
}

// 查看参训人员
const viewParticipants = (row) => {
  console.log('查看参训人员', row)
  ElMessage.info('查看参训人员')
}

// 编辑培训计划
const editProgram = (row) => {
  Object.assign(programForm, row)
  showAddDialog.value = true
}

// 删除培训计划
const deleteProgram = (row) => {
  ElMessageBox.confirm('确定要删除该培训计划吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = programList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      programList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 查看记录
const viewRecord = (row) => {
  console.log('查看记录', row)
  ElMessage.info('查看记录')
}

// 查看证书
const viewCertificate = (row) => {
  console.log('查看证书', row)
  ElMessage.success('证书查看功能')
}

// 编辑课程
const editCourse = (row) => {
  console.log('编辑课程', row)
  ElMessage.info('编辑课程功能')
}

// 查看课程内容
const viewCourseContent = (row) => {
  console.log('查看课程内容', row)
  ElMessage.info('查看课程内容')
}

// 删除课程
const deleteCourse = (row) => {
  ElMessageBox.confirm('确定要删除该课程吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = courseList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      courseList.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

// 查看评估
const viewEvaluation = (row) => {
  console.log('查看评估', row)
  ElMessage.info('查看评估详情')
}

// 提交表单
const handleSubmit = () => {
  programFormRef.value.validate((valid) => {
    if (valid) {
      console.log('提交表单', programForm)
      ElMessage.success('保存成功')
      showAddDialog.value = false
    }
  })
}

// 提交课程表单
const handleCourseSubmit = () => {
  console.log('提交课程', courseForm)
  ElMessage.success('课程添加成功')
  showCourseDialog.value = false
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}
</script>

<style scoped lang="scss">
.training-page {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.stats-row {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .stat-icon {
    width: 60px;
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
    margin-right: 15px;
  }

  .stat-content {
    flex: 1;

    .stat-value {
      font-size: 28px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 5px;
    }

    .stat-label {
      font-size: 14px;
      color: #909399;
    }
  }
}

.filter-card {
  margin-bottom: 20px;
}

.table-card {
  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

